'use strict';

const Controller = require('../core/base_controller');

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserController extends Controller {
  async logout() {
    // 删除存储的 JWT 令牌
    this.ctx.session = null;
    this.success({
      msg: '操作成功',
    });
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx } = this;
    try {
      const res = await ctx.service.user.getcurrentuser();
      this.success(res);
    } catch (error) {
      this.fail('获取失败');
    }
  }

  // 绑定组织
  async bind() {
    const { ctx } = this;
    try {
      const isinorg = await ctx.model.Org.findOne({
        where: {
          org_join_key: ctx.request.body.org_join_key,
        },
      });
      if (isinorg) {
        await ctx.service.user.update(
          {
            org_id: isinorg.dataValues.id,
            role_type: isinorg.dataValues?.org_join_key,
          },
          this
        );
      } else {
        this.fail('邀请码不存在');
      }
    } catch (error) {
      this.fail('获取失败');
    }
  }

  async index() {
    const ctx = this.ctx;
    const user = await ctx.service.user.getcurrentuser();
    const query = {
      org_id: user?.org_id,
    };
    const result = await ctx.model.User.findAll({
      where: query,
      attributes: {
        exclude: [ 'password' ],
      },
    });
    this.success(result);
  }

  async getallUsers() {
    const ctx = this.ctx;
    const result = await ctx.model.User.findAll({});
    this.success(result);
  }

  async show() {
    const ctx = this.ctx;
    const result = await ctx.model.User.findByPk(toInt(ctx.params.id));
    this.success(result);
  }

  async create() {
    const ctx = this.ctx;
    if (!ctx.request.body.user_name || !ctx.request.body.password) {
      this.fail('请完善必填项！');
      return;
    }
    const isaddon = await ctx.model.User.findOne({
      where: {
        user_name: ctx.request.body.user_name,
      },
    });
    if (isaddon) {
      this.fail('用户名已存在!');
    } else {
      const user = await ctx.model.User.create(ctx.request.body);
      this.success(user);
    }
  }

  async update() {
    const ctx = this.ctx;
    if (ctx.request.body.user_name) {
      const isaddon = await ctx.model.User.findOne({
        where: {
          user_name: ctx.request.body.user_name,
        },
      });
      if (isaddon) {
        this.fail('用户名已存在!');
      } else {
        await ctx.service.user.update(ctx.request.body, this);
      }
      return;
    }
    if (ctx.request.body.password) {
      const user = await ctx.service.user.getcurrentuser();
      if (ctx.request.body.oldpwd !== user?.password) {
        this.fail('旧密码校验失败!');
        return;
      }
      if (ctx.request.body.password !== ctx.request.body.cfpwd) {
        this.fail('新密码设置中两次密码不一致!');
        return;
      }
      await ctx.service.user.update(
        {
          password: ctx.request.body.password,
        },
        this
      );
      return;
    }
    await ctx.service.user.update(ctx.request.body, this);
  }

  async destroy() {
    const ctx = this.ctx;
    const id = toInt(ctx.params.id);
    const user = await ctx.model.User.findByPk(id);
    if (!user) {
      ctx.status = 404;
      ctx.body = {
        code: 1,
        success: false,
        msg: '库里没有该条数据',
      };
      return;
    }

    await user.destroy();
    this.success({
      data: '已删除',
    });
  }
}

module.exports = UserController;
